<template>
  <div class="announcement-management-container">
    <div class="page-header">
      <h2>公告管理</h2>
      <div class="actions">
        <el-button type="primary" @click="handleCreateAnnouncement">
          <el-icon><Plus /></el-icon>
          发布公告
        </el-button>
        <el-select v-model="statusFilter" placeholder="筛选状态" @change="handleStatusChange">
          <el-option label="全部公告" :value="''" />
          <el-option label="未发布" :value="0" />
          <el-option label="已发布" :value="1" />
        </el-select>
      </div>
    </div>
    
    <el-table
      v-loading="loading"
      :data="announcements"
      stripe
      border
      style="width: 100%"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column prop="id" label="ID" width="80" />
      
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="scope">
          <router-link 
            :to="`/announcements/${scope.row.id}`" 
            class="announcement-link"
          >
            {{ scope.row.title }}
          </router-link>
        </template>
      </el-table-column>
      
      <el-table-column prop="content" label="内容" min-width="250">
        <template #default="scope">
          {{ truncateText(scope.row.content, 50) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="isPublished" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isPublished ? 'success' : 'info'">
            {{ scope.row.isPublished ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="publishTime" label="发布时间" width="180" sortable>
        <template #default="scope">
          {{ scope.row.publishTime ? formatDate(scope.row.publishTime) : '未发布' }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            :type="scope.row.isPublished ? 'warning' : 'success'" 
            @click="handleTogglePublish(scope.row)"
          >
            {{ scope.row.isPublished ? '取消发布' : '发布' }}
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-if="total > 0"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="currentPage"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>
    
    <!-- 创建/编辑公告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑公告' : '创建公告'"
      width="800px"
    >
      <el-form
        ref="announcementFormRef"
        :model="announcementForm"
        :rules="formRules"
        label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        
        <el-form-item label="附件" v-if="isEdit">
          <p class="text-muted">编辑模式下无法修改附件，请到详情页面管理附件</p>
        </el-form-item>
        
        <el-form-item label="附件" v-else>
          <el-upload
            multiple
            :http-request="uploadFile"
            :file-list="fileList"
            :on-remove="handleRemoveFile"
            :before-upload="beforeUpload"
            :limit="5"
            :disabled="isEdit"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg、jpeg、png、pdf、doc、docx、xls、xlsx、zip格式，文件大小不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="announcementForm.isPublished">立即发布</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'AnnouncementManagement',
  components: {
    Plus
  },
  setup() {
    const store = useStore()
    const announcementFormRef = ref(null)
    
    // 公告列表相关数据
    const announcements = computed(() => store.getters.allAnnouncements)
    const total = computed(() => store.state.announcements.totalAll)
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const statusFilter = ref('')
    
    // 公告表单相关数据
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const announcementForm = reactive({
      id: null,
      title: '',
      content: '',
      isPublished: false
    })
    const fileList = ref([])
    const formRules = {
      title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
        { min: 3, max: 100, message: '标题长度应在3-100个字符之间', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' },
        { min: 10, max: 5000, message: '内容长度应在10-5000个字符之间', trigger: 'blur' }
      ]
    }
    
    // 获取公告列表
    const fetchAnnouncements = async () => {
      let status = null;
      if (statusFilter.value === 0 || statusFilter.value === '0') {
        status = 0;
      } else if (statusFilter.value === 1 || statusFilter.value === '1') {
        status = 1;
      }
      
      await store.dispatch('fetchAllAnnouncements', {
        page: currentPage.value,
        size: pageSize.value,
        status: status
      })
    }
    
    // 初始化
    onMounted(() => {
      fetchAnnouncements()
    })
    
    // 分页处理
    const handlePageChange = (page) => {
      currentPage.value = page
      fetchAnnouncements()
    }
    
    // 每页条数改变
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      fetchAnnouncements()
    }
    
    // 状态筛选改变
    const handleStatusChange = () => {
      currentPage.value = 1
      fetchAnnouncements()
    }
    
    // 文本截断
    const truncateText = (text, length) => {
      if (!text) return ''
      if (text.length <= length) return text
      return text.substring(0, length) + '...'
    }
    
    // 日期格式化
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    
    // 创建公告
    const handleCreateAnnouncement = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑公告
    const handleEdit = (announcement) => {
      isEdit.value = true
      Object.assign(announcementForm, announcement)
      dialogVisible.value = true
    }
    
    // 切换发布状态
    const handleTogglePublish = (announcement) => {
      ElMessageBox.confirm(
        announcement.isPublished ? '确定要取消发布该公告吗？' : '确定要发布该公告吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const result = await store.dispatch('togglePublishAnnouncement', {
            id: announcement.id,
            isPublished: !announcement.isPublished
          })
          
          if (result.success) {
            ElMessage.success(announcement.isPublished ? '公告已取消发布' : '公告已发布')
            await fetchAnnouncements()
          } else {
            ElMessage.error(result.message || '操作失败')
          }
        } catch (error) {
          ElMessage.error('操作失败，请重试')
        }
      }).catch(() => {})
    }
    
    // 删除公告
    const handleDelete = (announcement) => {
      ElMessageBox.confirm(
        '确定要删除该公告吗？此操作不可恢复！',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const result = await store.dispatch('deleteAnnouncement', announcement.id)
          
          if (result.success) {
            ElMessage.success('公告已删除')
            await fetchAnnouncements()
          } else {
            ElMessage.error(result.message || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败，请重试')
        }
      }).catch(() => {})
    }
    
    // 重置表单
    const resetForm = () => {
      announcementForm.id = null
      announcementForm.title = ''
      announcementForm.content = ''
      announcementForm.isPublished = false
      fileList.value = []
    }
    
    // 上传文件前验证
    const beforeUpload = (file) => {
      // 验证文件类型
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 
                           'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 
                           'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                           'application/zip', 'application/x-rar-compressed']
      
      if (!allowedTypes.includes(file.type)) {
        ElMessage.error('不支持的文件类型')
        return false
      }
      
      // 验证文件大小（5MB）
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        ElMessage.error('文件大小不能超过5MB')
        return false
      }
      
      return true
    }
    
    // 模拟上传
    const uploadFile = (options) => {
      fileList.value.push({
        name: options.file.name,
        raw: options.file
      })
      options.onSuccess()
    }
    
    // 移除文件
    const handleRemoveFile = (file) => {
      const index = fileList.value.findIndex(item => item.name === file.name)
      if (index !== -1) {
        fileList.value.splice(index, 1)
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!announcementFormRef.value) {
        ElMessage.error('表单引用不存在')
        return
      }

      loading.value = true
      try {
        const valid = await announcementFormRef.value.validate()
        
        if (!valid) {
          ElMessage.error('请填写完整的表单信息')
          return
        }

        const files = fileList.value.map(file => file.raw)
        const announcement = {
          title: announcementForm.title.trim(),
          content: announcementForm.content.trim(),
          isPublished: announcementForm.isPublished
        }

        if (isEdit.value) {
          announcement.id = announcementForm.id
          const result = await store.dispatch('updateAnnouncement', announcement)
          if (result.success) {
            ElMessage.success('公告更新成功')
            dialogVisible.value = false
            await fetchAnnouncements()
          } else {
            ElMessage.error(result.message || '更新失败')
          }
        } else {
          const result = await store.dispatch('createAnnouncement', { announcement, files })
          if (result.success) {
            ElMessage.success('公告创建成功')
            dialogVisible.value = false
            resetForm()
            await fetchAnnouncements()
          } else {
            ElMessage.error(result.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('提交表单时发生错误:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        loading.value = false
      }
    }
    
    return {
      announcements,
      total,
      loading,
      currentPage,
      pageSize,
      statusFilter,
      dialogVisible,
      isEdit,
      announcementForm,
      fileList,
      formRules,
      announcementFormRef,
      truncateText,
      formatDate,
      handlePageChange,
      handleSizeChange,
      handleStatusChange,
      handleCreateAnnouncement,
      handleEdit,
      handleTogglePublish,
      handleDelete,
      beforeUpload,
      uploadFile,
      handleRemoveFile,
      submitForm
    }
  }
}
</script>

<style scoped>
.announcement-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.announcement-link {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.announcement-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.text-muted {
  color: #909399;
  font-size: 0.9rem;
}
</style> 